package com.time.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.time.vo.ResultVO;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author mjw
 * @date 2022/11/29
 */
//public class SecurityAuthenticationFailureHandler implements AuthenticationFailureHandler {
//
//    /**
//     * AuthenticationException:异常信息
//     */
//    @Override
//    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//        response.setHeader("Content-Type", "application/json;charset=utf-8");
//        PrintWriter writer = response.getWriter();
//        ResultVO<Object> resultVO = new ResultVO<>(500, exception.getMessage(), null);
//        writer.print(new ObjectMapper().writeValueAsString(resultVO));
//        writer.flush();
//        writer.close();
//    }
//}

public class SecurityAuthenticationFailureHandler extends ExceptionMappingAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //直接输出json格式的响应信息
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        ResultVO resultVO = new ResultVO(500, exception.getMessage(), null);
        out.write(new ObjectMapper().writeValueAsString(resultVO));
        out.flush();
        out.close();
    }
}
